﻿$(function(){
	var recordPath1;
	var recordPath2;
	var countdown = 180; 
	var isPlay = 0;
	$("#openbtn").click(function(){
		$('head').append('<link rel="stylesheet" href="/public/yx/css/record2.css">');
		
		
		if(isPlay == 0){
			isPlay = 1;
			wx.startRecord();
			settime();
			$("#openbtn").text("停止录音");
		} else{
			isPlay = 0;
			wx.stopRecord({
    				success: function (res) {
        				recordPath2 = res.localId
   			 	}
			});
			countdown=0;
			$("#openbtn").text("开始录音");
			removejscssfile("/public/yx/css/record2.css", "css");
			
		}
		wx.onVoiceRecordEnd({
    				// 录音时间超过一分钟没有停止的时候会执行 complete 回调
    				complete: function (res) {
       				recordPath1 = res.localId; 
				wx.startRecord();
    			}
		});
	});
	
	$("#testlisten").click(function(){
		$('head').append('<link rel="stylesheet" href="/public/yx/css/record2.css">');
		var stre = document.getElementById("testlisten").innerText;
		var recordStr = "试听";
		if(stre == recordStr){

			wx.playVoice({
    				localId: recordPath1 // 需要播放的音频的本地ID，由stopRecord接口获得
				
				});
			
			
			$("#testlisten").text("结束");
		} else{
			wx.stopVoice({
    				localId: recordPath // 需要停止的音频的本地ID，由stopRecord接口获得

			});
			removejscssfile("/public/yx/css/record2.css", "css");
				
			$("#testlisten").text("试听");
		}
		
		wx.onVoicePlayEnd({
    			success: function (res) {
        			wx.playVoice({
    					localId: recordPath2 // 需要播放的音频的本地ID，由stopRecord接口获得
				
				});
    			}
		});
	});
	

	function settime() { 
    		if (countdown == 0) { 
        		countdown = 180; 
        		$("#timecount").text(180);
        		return;
    		} else { 
        		$("#timecount").text(countdown);
        		countdown--; 
    		} 
	setTimeout(function() { 
	    settime() }
	    ,1000) 
	}	
});

function removejscssfile(filename, filetype) {
	var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none"
	var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none"
	var allsuspects = document.getElementsByTagName(targetelement)
	for(var i = allsuspects.length; i >= 0; i--) {
		if(allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
			allsuspects[i].parentNode.removeChild(allsuspects[i])
	}
}




